/**
 * 数据库创建脚本生成器。
 *
 * @author fenglinz
 * @since 2019-4-1
 */
class CreateSqlBuilder {
    /**
     * 构造函数
     * @param {Object} meta 元数据
     */
    constructor(tableName, meta) {
        this.columns = [];
        this.tableName = tableName;

        this._resolve(meta);
    }

    /**
     * 生成sql脚本
     */
    build() {
        if (this.columns.length > 0) {
            let columnSegments = [];
            let valueSegments = [];

            this.columns.forEach(c => {
                columnSegments.push(c.columnName);
                valueSegments.push(`@${c.propName}`);
            });

            return `INSERT INTO ${this.tableName} (${columnSegments.join(",")}) VALUES(${valueSegments.join(",")})`;
        }
    }

    /**
     * 获取数据对象
     */
    values(data) {
        let entityObject = {};

        this.columns.forEach(c => {
            entityObject[c.propName] = (data[c.propName] && data[c.propName].value) || data[c.propName];
        });

        return entityObject;
    }

    /**
     * 解析元数据
     */
    _resolve(meta) {
        let props = Object.getOwnPropertyNames(meta);

        props.forEach(prop => {
            this.columns.push({
                propName: prop,
                columnName: (meta[prop] && meta[prop].column) || prop
            });
        });
    }
}

module.exports = CreateSqlBuilder;